/**
 * 书签模型
 * 用于存储和管理书签信息
 */

const mongoose = require('mongoose');

// 定义书签模式
const BookmarkSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, '请提供书签标题'],
    trim: true,
    maxlength: [200, '标题不能超过200个字符']
  },
  url: {
    type: String,
    required: [true, '请提供书签URL'],
    match: [
      /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/,
      '请提供有效的URL'
    ]
  },
  description: {
    type: String,
    maxlength: [1000, '描述不能超过1000个字符']
  },
  favicon: {
    type: String, // 存储网站图标的URL
    default: null
  },
  tags: {
    type: [String],
    default: []
  },
  category: {
    type: mongoose.Schema.ObjectId,
    ref: 'Category',
    required: [true, '请选择一个分类']
  },
  isPublic: {
    type: Boolean,
    default: true
  },
  clickCount: {
    type: Number,
    default: 0
  },
  lastClickedAt: {
    type: Date,
    default: null
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

// 更新时自动更新updatedAt字段
BookmarkSchema.pre('save', function(next) {
  if (this.isModified() && !this.isNew) {
    this.updatedAt = Date.now();
  }
  next();
});

// 点击书签时更新计数和最后点击时间
BookmarkSchema.methods.incrementClickCount = async function() {
  this.clickCount += 1;
  this.lastClickedAt = Date.now();
  await this.save();
  return this;
};

module.exports = mongoose.model('Bookmark', BookmarkSchema); 